<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" style="padding-right: 5px;">
      <el-row>
        <el-col :span="8">
          <el-form-item label="状态" prop="status" style="width: 90%">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option
                v-for="dict in status_types"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <!--<el-col :span="8">
          <el-form-item label="积分类型" prop="wayType" style="width: 90%">
            <el-select v-model="queryParams.wayType" placeholder="请选择积分类型" clearable>
                <el-option
                  v-for="dict in wayType_types"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>-->
      </el-row>
    </el-form>
    

    <el-row :gutter="10" class="mb8" style="margin: 15px 0px;">
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Plus"
          @click="handleAdd(null)"
          v-hasPermi="['partybuilding:ScoreType:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Sort"
            @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" @handleQuery="handleQuery" @resetQuery="resetQuery"></right-toolbar>
    </el-row>

    <div class="tip_info">
      <el-icon :size="17" style="margin-right: 7px;position: relative;top: 2px;color: #1890ff;"><InfoFilled /></el-icon>
      <span style="color: #000!important;">申报积分规则管理员可自主设置积分项，可通过启动和禁用控制积分规则展示，已设置的申报积分项不可再次编排积分内容，已经确认的积分记录保留。</span>
    </div>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="scoreTypeList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="分类" align="left" prop="name" min-width="393px"/>
      <el-table-column label="分制" align="center" prop="bouns" width="90px">
        <template #default="scope">
          <span v-if="scope.row.level === 0">&nbsp;</span>
          <span v-else>{{ scope.row.bouns === 0 ? "减分" : "加分" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="基本分" align="center" prop="basisScore" width="110px"/>
      <el-table-column label="最高分" align="center" prop="highScore" width="110px"/>
      <el-table-column label="周期" align="center" prop="scoreDayUp" width="110px">
        <template #default="scope">
          <span v-if="scope.row.level === 0">&nbsp;</span>
          <div v-else>
            <span v-if="scope.row.cycle === 0">月度</span>
            <span v-else-if="scope.row.cycle === 1">季度</span>
            <span v-else-if="scope.row.cycle === 2">半年</span>
            <span v-else-if="scope.row.cycle === 3">年度</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="110px">
        <template #default="scope">
          <span v-if="scope.row.level === 0">&nbsp;</span>
          <span v-else>{{ scope.row.status === 0 ? "停用" : "启用" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
        <template #default="scope">
          <el-button link type="danger" @click="handleUpdate(scope.row)" v-hasPermi="['partybuilding:ScoreType:edit']">编辑</el-button>
          <el-divider direction="vertical" />
          <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['partybuilding:ScoreType:remove']" v-if="scope.row.level === 0">删除</el-button>
          <el-button link type="danger" @click="handleStatus(scope.row)" v-hasPermi="['partybuilding:ScoreType:edit']" v-else>{{ scope.row.status === 0 ? "启用" : "停用" }}</el-button>
          <el-divider direction="vertical" />
          <el-button link type="danger" @click="handleAdd(scope.row)" v-hasPermi="['partybuilding:ScoreType:add']" v-if="scope.row.level === 0">新增规则</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加或修改积分类型对话框分类 -->
    <el-dialog v-if="refreshTable" :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ScoreTypeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="积分分类" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改积分类型对话框规则 -->
    <el-dialog :title="titleRule" v-model="openRule" width="900px" append-to-body>
      <el-form ref="ScoreTypeRef" :model="form" :rules="rules" label-width="109px">
        <el-row>
          <!--<el-col :span="12">
            <el-form-item label="积分类型" prop="name">
              <el-radio-group v-model="form.wayType">
                <el-radio value="0">申报积分</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item label="分类" prop="parentName">
              <el-input v-model="form.parentName" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分制" prop="bouns">
              <el-radio-group v-model="form.bouns" :disabled="isDisabledEdit">
                <el-radio v-for="item in bouns_types" :key="item.value" :label="item.label" :value="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基本分" prop="basisScore">
              <el-input-number v-model="form.basisScore" placeholder="请输入基本分" maxlength="5" style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最高分" prop="highScore">
              <el-input-number v-model="form.highScore" placeholder="请输入最高分" maxlength="5" style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="每日积分上限" prop="scoreDayUp">
              <el-input-number v-model="form.scoreDayUp" placeholder="请输入每日积分上限" maxlength="5" style="width: 43%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="周期" prop="cycle">
              <el-select v-model="form.cycle" placeholder="请选择周期" clearable :disabled="isDisabledEdit">
                <el-option
                  v-for="dict in cycle_types"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status" :disabled="isDisabledEdit">
                <el-radio v-for="item in status_types" :key="item.value" :label="item.label" :value="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容" prop="name">
              <el-input type="textarea" v-model="form.name" rows="5" placeholder="请输入内容" :disabled="isDisabledEdit"/>
            </el-form-item>
          </el-col>
        </el-row>
        
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormRule">确 定</el-button>
          <el-button @click="cancelRule">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ScoreTypeOrg">
import { listScoreType, getScoreType, delScoreType, updateScoreType, addCategory, addRule } from "@/api/partybuilding/ScoreType";

const { proxy } = getCurrentInstance();

const scoreTypeList = ref([]);
const scoreTableList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const isExpandAll = ref(false);
const refreshTable = ref(true);
const openRule = ref(false);
const titleRule = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 100000,
    name: null,
    type: 0,
    parentId: null,
    level: null,
    subtitle: null,
    bouns: null,
    basisScore: null,
    highScore: null,
    cycle: null,
    status: null,
    wayType: null,
    scoreDayUp: null,
    orderByName:"sort"
  },
  rules: {
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    cycle: [
      { required: true, message: "周期不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "0个人积分，1组织积分不能为空", trigger: "change" }
    ],
    level: [
      { required: true, message: "级别,1分类，2题目不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
const wayType_types = ref([{label: '申报积分', value: '0'}, {label: '自动积分', value: '1'}]);
const bouns_types = ref([{label: '加分', value: '1'}, {label: '减分', value: '0'}]);
const status_types = ref([{label: '启用', value: '1'}, {label: '停用', value: '0'}]);
const cycle_types = ref([{label: '月度', value: '0'}, {label: '季度', value: '1'}, {label: '半年', value: '2'}, {label: '年度', value: '3'}]);
const isDisabledEdit = ref(false);


/** 查询积分类型列表 */
function getList() {
  loading.value = true;
  listScoreType(queryParams.value).then(response => {
    scoreTableList.value = response.rows;
    scoreTypeList.value =proxy.handleTree(response.rows);
    // total.value = response.total;
    loading.value = false;
  });
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    type: 0,
    parentId: null,
    level: null,
    subtitle: null,
    bouns: null,
    basisScore: null,
    highScore: null,
    cycle: null,
    status: null,
    wayType: null,
    scoreDayUp: null
  };
  proxy.resetForm("ScoreTypeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  if (row) {
    form.value.parentId = row.id;
    openRule.value = true;
    titleRule.value = "添加党员积分规则";
    form.value.type = 0; //0个人积分，1组织积分
    form.value.level = 1; //级别,0分类，1题目
    form.value.wayType = '0'; //0申报积分，1自动积分
    form.value.status = '1'; //状态,0停用，1启用    
    isDisabledEdit.value = false;
  }else{
    open.value = true;
    title.value = "添加党员积分类型";
    form.value.type = 0; //0个人积分，1组织积分
    form.value.level = 0; //级别,0分类，1题目
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getScoreType(_id).then(response => {
    form.value = response.data;
    if (form.value.level == 0) {
      open.value = true;
      title.value = "修改积分类型";
    } else {
      openRule.value = true;
      titleRule.value = "修改积分规则";
      form.value.cycle = form.value.cycle+''; //周期,0月度，1季度，2半年，3年度
      form.value.bouns = form.value.bouns+''; //分制,0减分，1加分
      form.value.status = form.value.status+''; //状态,0停用，1启用
      isDisabledEdit.value = true;
      // 获取积分分类
      let parentId = form.value.parentId;
      scoreTableList.value.forEach(item => {
        if (item.id == parentId) {
          form.value.parentName = item.name;
        }
      });
    }
  });
}

// 启用/停用按钮操作
function handleStatus(row) {
  let obj = JSON.parse(JSON.stringify(row));
  let title = obj.status === 0 ? "启用" : "停用";
  obj.status = obj.status === 0 ? 1 : 0;
  proxy.$modal.confirm('是否确认'+title+'积分【' + row.name + '】的数据项？').then(function() {
    return updateScoreType(obj);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess(title+"成功");
  }).catch(() => {});
}

/** 提交分类按钮 */
function submitForm() {
  proxy.$refs["ScoreTypeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateScoreType(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 提交规则按钮 */
function submitFormRule() {
  proxy.$refs["ScoreTypeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateScoreType(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openRule.value = false;
          getList();
        });
      } else {
        addRule(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openRule.value = false;
          getList();
        });
      }
    }
  });
}


// 取消按钮
function cancelRule() {
  openRule.value = false;
  reset();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除积分【' + row.name + '】的数据项？').then(function() {
    return delScoreType(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('partybuilding/ScoreType/export', {
    ...queryParams.value
  }, `ScoreType_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style lang="scss" scoped>
.tip_info {
    box-sizing: border-box;
    margin: 0;
    color: rgba(0, 0, 0, .65);
    font-size: 14px;
    font-variant: tabular-nums;
    line-height: 1.5;
    list-style: none;
    -webkit-font-feature-settings: "tnum";
    font-feature-settings: "tnum";
    position: relative;
    padding: 8px 15px;
    word-wrap: break-word;
    border-radius: 4px;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    margin-top: 19px;
}
</style>